package com.che.libcommon.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

public class IntentUtils {

  public static Intent getPickGallery(){
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setDataAndType(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    return intent;
  }

  public static String extraImageFromGallery(Context context,Intent intent){
    Uri uri = intent.getData();
    if (uri == null) {
      return null;
    }
    final String scheme = uri.getScheme();
    String data = null;
    if (scheme == null) {
      data = uri.getPath();
    } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
      data = uri.getPath();
    } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
      Cursor cursor = null;
      try {
        cursor = context.getContentResolver().query(uri,
            new String[]{MediaStore.Images.ImageColumns.DATA},
            null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
          int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
          if (index > -1) {
            data = cursor.getString(index);
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }
    }
    return data;
  }

}
